package com.tjf.traffic;

import android.app.usage.NetworkStatsManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tjf.traffic.adapter.TrafficAppAdapter;
import com.tjf.traffic.bean.TrafficInfo;
import com.tjf.traffic.utils.NetworkStatsHelper;
import com.tjf.traffic.bean.TrafficBean;
import com.tjf.traffic.utils.TrafficFormat;
import com.tjf.traffic.utils.TrafficManagerApp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 应用流量排行APP页   进行今日和今月列表切换  App流量的排行展示
 */
public class TrafficAppActivity extends AppCompatActivity {

    @BindView(R.id.traffic_list_rev)
    RecyclerView trafficListRev;
    @BindView(R.id.traffic_day_month_tv)
    TextView trafficDayMonthTv;
    @BindView(R.id.total_traffic_tv)
    TextView totalTrafficTv;
    @BindView(R.id.total_up_traffic_tv)
    TextView totalUpTrafficTv;
    @BindView(R.id.total_down_traffic_tv)
    TextView totalDownTrafficTv;
    @BindView(R.id.traffic_goback)
    ImageView trafficGoback;

    TrafficAppAdapter trafficAppAdapter;
    NetworkStatsManager networkStatsManager = null;
    NetworkStatsHelper helper;

    List<TrafficInfo> trafficApplist = new ArrayList<>();
    TrafficManagerApp trafficManagerApp;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_traffic_app);
        ButterKnife.bind(this);
        trafficManagerApp = new TrafficManagerApp(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            networkStatsManager = (NetworkStatsManager) getSystemService(NETWORK_STATS_SERVICE);
        }
        helper = new NetworkStatsHelper(networkStatsManager);
        getDayAndMonthInfo(true);
        trafficAppAdapter = new TrafficAppAdapter(this,
                trafficApplist, R.layout.traffic_app_item);
        trafficListRev.setLayoutManager(new LinearLayoutManager(this));
        trafficListRev.setAdapter(trafficAppAdapter);


        trafficDayMonthTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (trafficDayMonthTv.getText().toString().equals("今日")) {
                    trafficDayMonthTv.setText("今月");
                    getDayAndMonthInfo(false);
                } else if (trafficDayMonthTv.getText().toString().equals("今月")) {
                    trafficDayMonthTv.setText("今日");
                    getDayAndMonthInfo(true);
                }
                Toast.makeText(TrafficAppActivity.this,
                        "点击了" + trafficDayMonthTv.getText().toString(), Toast.LENGTH_SHORT).show();
                if (trafficAppAdapter != null) {
                    trafficAppAdapter.notifyDataSetChanged();
                }
            }
        });
        trafficGoback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public void getDayAndMonthInfo(boolean isDayAndMonth) {
        trafficApplist.clear();
        trafficApplist.addAll(trafficManagerApp.getInternetTrafficInfos());
        long totalTx = 0;
        long totalRx = 0;
        long totalTraffic;
        for (TrafficInfo trafficInfo : trafficApplist) {
            helper.setPackageUid(trafficInfo.getUid());
            TrafficBean trafficBean = helper.getSummaryTrafficMobile(this, isDayAndMonth);
            trafficInfo.setTraffic(TrafficFormat.formatByte(trafficBean.getTotalData()));
            trafficInfo.setMobleTotalData(trafficBean.getTotalData());
            trafficInfo.setMobleRxBytes(trafficBean.getRxBytes());
            trafficInfo.setMobleTxBytes(trafficBean.getTxBytes());
            totalTx += trafficBean.getTxBytes();
            totalRx += trafficBean.getRxBytes();
        }
        totalTraffic = totalRx + totalTx;

        Log.i("流量-", "==流量的汇总==\n"
                + TrafficFormat.formatByte(totalTraffic)
                + "\n上传流量合计：" +
                TrafficFormat.formatByte(totalTx)
                + "\n下载流量合计：" + TrafficFormat.formatByte(totalRx));

        setTotalTraffic(TrafficFormat.formatByte(totalTraffic),
                TrafficFormat.formatByte(totalTx), TrafficFormat.formatByte(totalRx));

        for (int i = trafficApplist.size() - 1; i >= 0; i--) {
            TrafficInfo trafficInfo = trafficApplist.get(i);
            if (trafficInfo.getTraffic().startsWith("0")) {
                trafficApplist.remove(i);
            }
        }
        Log.i("流量-", "过滤后的app的数量=" + trafficApplist.size());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Collections.sort(trafficApplist, new Comparator<TrafficInfo>() {
                @Override
                public int compare(TrafficInfo o1, TrafficInfo o2) {
                    //流量最大值排列
                    int max = (int) (o2.getMobleTotalData() - o1.getMobleTotalData());
                    return max;
                }
            });
        }
    }


    /**
     * 流量合计
     */
    public void setTotalTraffic(String totalTraffic, String upTraffic, String downTraffic) {
        totalTrafficTv.setText(String.format("总流量：%s", totalTraffic));

        totalUpTrafficTv.setText(String.format("上传总流量：%s", upTraffic));

        totalDownTrafficTv.setText(String.format("下载总流量：%s", downTraffic));

    }
}